<?php
/**
 * Created by PhpStorm.
 * User: flydany
 * Date: 2018/3/21
 * Time: 22:18
 */
namespace common\models;

use Yii;

/**
 * This is the model class for table "UserBond".
 */
class UserBond extends ActiveRecord {

    // 订单号前缀
    const SnPrefix = 'UB';

    // 保证金额度
    const BondAmount = 1;

    // 状态
    // @describe 状态流转图
    // @describe 待付款 -> 付款成功/付款失败
    const StatusInit = 0;
    const StatusSuccess = 10;
    const StatusFail = 11;
    public static $statusSelector = [
        self::StatusInit => ['title' => '待付款', 'status' => 'gray'],
        self::StatusSuccess => ['title' => '付款成功', 'status' => 'blue'],
        self::StatusFail => ['title' => '付款失败', 'status' => 'green'],
    ];

    // only define rules for those attributes that
    // will receive user inputs.
    public function rules()
    {
        return [
            [['order_number', 'user_id', 'platform', 'amount'], 'required'],
            [['user_id', 'platform', 'amount', 'success_at', 'paydate', 'status', 'deleted_at'], 'integer'],
            [['order_number', 'account'], 'string', 'max' => 32],
            [['remark'], 'string', 'max' => 255],
        ];
    }
    /**
     * 字段名称
     * @return array
     */
    public function attributeLabels()
    {
        return [
            'order_number' => '订单号',
            'user_id' => '设计师',
            'platform' => '支付通道',
            'account' => '账号',
            'amount' => '金额',
            'success_at' => '成功时间',
            'paydate' => '清算日期',
            'status' => '状态',
            'remark' => '备注',
            'deleted_at' => '删除时间',
        ];
    }

    /**
     * @name update & insert data check config for html
     * @param $type string 操作类型
     * @param $encodeJson boolean 是否转成JSON字符串
     * @return string | array
     */
    public static function flyer($type = 'update')
    {
        return [
            'param' => [
                // 'user_id' => ['用户编号', ['int', 'required']],
                'platform' => ['支付通道', ['inkey' => Recharge::$platformSelector, 'required']],
                // 'amount' => ['金额', ['int', 'required']],
            ],
        ];
    }

    /**
     * 支付成功
     * @param $account string 支付账户
     * @param $amount integer 充值金额
     * @return boolean
     */
    public function success($account, $amount)
    {
        if($this->deleted()) {
            return false;
        }
        if( ! in_array($this->status, [static::StatusInit])) {
            return false;
        }
        if($this->amount != $amount) {
            return false;
        }
        $this->account = $account;
        $this->status = static::StatusSuccess;
        $this->paydate = date('Ymd');
        $this->updated_at = time();
        $this->success_at = time();
        return $this->transaction(function($db) {
            if( ! $this->save()) {
                throw new \Exception('system error');
            }
            // 修改用户资金流水变化
            /** @var UserAccount $userAccount */
            $userAccount = $this->user->account;
            if(empty($userAccount)) {
                throw new \Exception('user account don\'t exists');
            }
            // 添加充值记录
            $recharge = [
                'order_number' => $this->order_number,
                'user_id' => $this->user->id,
                'platform' => $this->platform,
                'amount' => $this->amount,
                'fee' => 0,
                'realname' => $this->user->realname,
                'mobile' => $this->user->mobile,
                'remark' => '支付雇佣费用',
                'status' => Recharge::StatusSuccess,
            ];
            if( ! Recharge::creator($recharge)) {
                throw new \Exception('create recharge order error');
            }
            // 增加充值流水
            if( ! $userAccount->recharge($this->amount)) {
                throw new \Exception('create user account log error');
            }
            // 增加支付流水
            if( ! $userAccount->bond($this->amount)) {
                throw new \Exception('update user account change error');
            }
            if( ! $this->user->setBond(User::BondStatusMoney)) {
                throw new \Exception('update bond status error');
            }
            $userTime = new UserTime();
            if( ! $userTime->setBondtime($this->user_id)) {
                throw new \Exception('update setBondtime   error');
            }
            return true;
        });
    }

    /**
     * 支付失败
     * @param $account string 支付账户
     * @return boolean
     */
    public function failed($account)
    {
        if($this->deleted()) {
            return false;
        }
        if( ! in_array($this->status, [static::StatusInit])) {
            return false;
        }
        $this->account = $account;
        $this->status = static::StatusFail;
        $this->updated_at = time();
        return $this->save();
    }

    /**
     * 获取employer信息
     * @return \yii\db\ActiveQuery
     */
    public function getUser()
    {
        return $this->hasOne(User::className(), ['id' => 'user_id']);
    }

    /**
     * 创建保证金订单
     * @return mixed
     */
    public static function creator($params)
    {
        if(empty($params)) {
            return false;
        }
//        $params['bond'] = bcmul($params['bond'], 100);
        $bond = new static();
        $bond->loads($params);

        $bond->user_id = Yii::$app->user->id;
        $bond->order_number = static::generateOrderNumber();
        $bond->amount = $params['bond'];
        $bond->status = static::StatusInit;
        if( ! ($bond->validate() && $bond->save())) {
            return false;
        }
        return $bond;
    }

    /**
     * 生成订单号
     * @return string
     */
    public static function generateOrderNumber()
    {
        return strtoupper(static::SnPrefix.base_convert((microtime(true) * 10000).rand(10000, 99999).rand(10000, 99999), 10, 36));
    }
}